package com.jiazhuo.blockgamesquare.http


import com.epc.easypurchase.BuildConfig
import com.jiazhuo.blockgamesquare.http.api.ApiService
import com.jiazhuo.blockgamesquare.http.api.UrlConstainer

import java.util.concurrent.TimeUnit

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory


/**
 * Created by chenwuchao on 2018/8/21.
 */

class RetrofitUtil {


    companion object {
        var api: ApiService? = null
            get() {
                if (field == null) {
                    throw IllegalArgumentException("please init Retrofit first!")
                }
                return field
            }

       private var mInstance: RetrofitUtil? = null

        @Synchronized  fun getInstance():RetrofitUtil{
            if (mInstance == null) mInstance = RetrofitUtil()
            return mInstance as RetrofitUtil
        }

    }

    /**
     * 网络引擎初始化
     */
    fun init() {
        //声明日志类
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        //设定日志级别
        if (BuildConfig.DEBUG) {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
        }
        val clientBuilder = OkHttpClient.Builder()
        clientBuilder.connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(httpLoggingInterceptor)
        val retrofit = Retrofit.Builder()
                .client(clientBuilder.build())
                .baseUrl(UrlConstainer.appBaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        api = retrofit.create(ApiService::class.java)
    }



}
